import { concatMap } from 'rxjs/operators';
import { of } from 'rxjs/internal/observable/of';
import { isNotNil } from '@shared/apes/core/util/check';
import { User } from '../../../../domain/user-info-model';


export function bindWS() {
  return function(target:Function) {
    // 初始化函数
    let ngOnInit = target.prototype.ngOnInit
      ? target.prototype.ngOnInit : function(){};
    let ngOnDestroy = target.prototype.ngOnDestroy
      ? target.prototype.ngOnDestroy : function(){};

    target.prototype.ngOnInit = function(...args: any[]): any {
      checkData(this);

      ngOnInit.apply(this, args); // 执行原始初始化函数


      // 当前登录人员信息
      let userAccount:User = this.userAuthService.getUserInfoObj().userAccount;


      const message = JSON.stringify({"appletId":this.params.applet.id,"topic":"ws.openAppletConnect",
      postId:userAccount.post.id ,userId: userAccount.id});
      this.ws.send(message);// 通知服务端发送消息

      // 订阅消息
      this.messagesSubscription = this.ws.messagesObserver.pipe(concatMap(data => of(data)))
        .subscribe(item => {
          const data = JSON.parse(item);
          // 如果当前主题为小程序信息并且指向当前小程序
          if(data.topic === "ws.appletMessage" && data.appletId === this.params.applet.id){
            console.log("lalalalalla");
            this.callback(this.obj);
          }
        });
    };


    target.prototype.ngOnDestroy = function(...args: any[]): any {
      const message = JSON.stringify({"appletId":this.params.applet.id,"topic":"ws.closeAppletConnect"});
      this.ws.send(message); // 通知服务端取消发送
      this.messagesSubscription.unsubscribe(); // 取消订阅
      ngOnDestroy.apply(this, args);
    }
  }
}

/***
 * 验证数据
 * @param self
 */
function checkData(self:any) {
  if(!isNotNil(self.userAuthService)) throw new Error("请注入UserAuthService服务，并命名为userAuthService");
  if(!isNotNil(self.ws)) throw new Error("请注入websocketService服务，并命名为ws");
  if(!isNotNil(self.params)) throw new Error("传入数据params不能为空");
  if(!isNotNil(self.params.widgetApi)) throw new Error("传入数据params的调用接口widgetApi不能为空");
  if(!isNotNil(self.callback)) throw new Error("回调函数callback不能为空");
}
